package com.cyou.gamehistory.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cyou.framework.util.StringUtility;
import com.sohu.fzBranch.SohuPassport;

/**
 * webutil
 * @author wangzhang
 * date 2012-12-24 下午4:59:38
 */
public class WebUtil {
	/**
	 * 获取客户端真实ip
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
	/**
	 * 用户登录后，通过此方法获取uid
	 * @param request
	 * @param response
	 * @return
	 */
	public static Integer returnUserId(HttpServletRequest request, HttpServletResponse response){
		SohuPassport passport = new SohuPassport(request, response);
        if (passport.userAuth() && passport.isActivated() && passport.isCertificateEmail()) {
        	return Integer.parseInt(passport.getUserInfo("user_id"));
        }
        return 0;
	}
	/**
	 * 校验用户是否登录
	 * @param req
	 * @param res
	 * @return
	 */
	public static boolean isLogin(HttpServletRequest req,HttpServletResponse res){
		SohuPassport passport = new SohuPassport(req, res);
		boolean flag = false;
		try{
			flag = passport.userAuth()&&passport.isActivated()&&passport.isCertificateEmail();
			return flag;
		}catch(Exception e){
			return flag;
		}
	}
	/**
	 * 根据登录passport获取用户头像地址
	 * @param passport
	 * @return
	 */
	public static String staticGetHeadshot(String passport){
		if(StringUtility.isNotBlank(passport)){
			int count=0;
			String pass = passport.toLowerCase();
			if(pass.indexOf("@17173.com")>0)
			{
				pass = pass.substring(0, pass.indexOf("@17173.com"));
			}
			String faceStr = pass+"/face.jpg";
			pass = pass.toLowerCase();
			for(int i=0; i<faceStr.length(); i++)
			{
				count += faceStr.substring(i,i+1).charAt(0);
			}
			int num = Math.round(count%3)==0 ? 3 : Math.round(count%3);
			faceStr = pass+"/faces.jpg";
			if(pass.length()<3){
				return "http://ue1.17173.itc.cn/imgface/noface.jpg";
			}
			String userFace = pass.substring(0,1)+"/"+pass.substring(1,2)+"/"+pass.substring(2,3)+"/"+faceStr;
			return "http://ue"+num+".17173.itc.cn/imgface/"+userFace;
		}
		return "http://ue1.17173.itc.cn/imgface/noface.jpg";
	}
}
